package com.gamemost.templestay;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;

import com.gamemost.dao.XMLProvider;
import com.gamemost.entity.BookRecent;
import com.gamemost.entity.BookStand;
import com.gamemost.layout.LayoutGridBook;
import com.gamemost.layout.LayoutMainScreen;
import com.gamemost.managers.LayoutManager;
import com.gamemost.managers.ResourcesManager;
import com.gamemost.templestay.R;

public class DownloadImageService extends AsyncTask<String, String, String[]> {
	ProgressDialog dialog;	
	public String nameimg = "imgbook";
	public int type;
	public int size = 0;
	public int sizebookstand = 0;

	public DownloadImageService(int type) {
		this.type = type;
		ResourcesManager.ac.waitDialog.show();
	}

	public void setSize(int s) {
		this.size = s;
	}

	public void setSizeBookStand(int s) {
		this.sizebookstand = s;
	}

	@Override
	protected String[] doInBackground(String... params) {
		// TODO Auto-generated method stub

		for (int i = 0; i < params.length; i++) {
			if (params[i] != null && !params[i].equals("")
					&& params[i].contains("http:")) {
				int count;
				try {
					URL url = new URL(params[i]);
					URLConnection conection = url.openConnection();
					conection.connect();
					int lenghtOfFile = conection.getContentLength();
					InputStream input = new BufferedInputStream(
							url.openStream());
					String[] listElm = params[i].split("/");
					nameimg = listElm[listElm.length - 1];
					nameimg = nameimg.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\s]", "");
					OutputStream output = null;
					if (type == 0) {
						output = new FileOutputStream(Environment
								.getExternalStorageDirectory().getPath()
								+ Config.IMAGE_BOOK + "/" + nameimg);
					} else if (type == 1) {
						output = new FileOutputStream(Environment
								.getExternalStorageDirectory().getPath()
								+ Config.IMAGE_STAND + "/" + nameimg);
					} else if (type == 2) {
						output = new FileOutputStream(Environment
								.getExternalStorageDirectory().getPath()
								+ Config.IMAGE_STAND_INLIST + "/" + nameimg);
					}
					byte data[] = new byte[1024];
					long total = 0;
					while ((count = input.read(data)) != -1) {
						total += count;
						output.write(data, 0, count);
					}
					output.flush();
					output.close();
					input.close();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ResourcesManager.ac.waitDialog.hide();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		return params;
	}

	@Override
	protected void onPostExecute(String[] result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if (type == 0) {
			ArrayList<BookRecent> list = ResourcesManager.ac.listBookRecent;
			int period = size;
			for (int i = 0; i < result.length; i++) {
				String name = result[i];
				if (!"".equals(name) && name != null && name.contains("http:")) {
					String[] listElm = name.split("/");
					nameimg = listElm[listElm.length - 1];
					nameimg = nameimg.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\s]", "");
					String imagePath = Environment
							.getExternalStorageDirectory().toString()
							+ Config.IMAGE_BOOK + "/" + nameimg;
					File f = new File(imagePath);
					list.get(i + period).setImage(nameimg);
					Bitmap bitmap = decodeFile(f);
					Bitmap bmp = Bitmap.createScaledBitmap(bitmap,
							 2*ResourcesManager.ac.width / 7,
							ResourcesManager.ac.height / 4, true);
					list.get(i + period).setBitmap(bmp);

				} else {
					Drawable drawable = ResourcesManager.ac.getResources()
							.getDrawable(R.drawable.no_book_cover);
					if (drawable instanceof BitmapDrawable) {
						Bitmap bmp = Bitmap.createScaledBitmap(((BitmapDrawable) drawable).getBitmap(),
								2 * ResourcesManager.ac.width / 7,
								ResourcesManager.ac.height / 4, true);
						list.get(i + period).setBitmap(bmp);
					}

				}

			}			
		
			LayoutMainScreen.getInstance().mAdapterNewBook.setListNewBook(list);
			LayoutMainScreen.getInstance().mAdapterNewBook
					.notifyDataSetChanged();
			try {
				XMLProvider.creatBookRecentXML(list);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TransformerException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ResourcesManager.ac.waitDialog.hide();
		} else if (type == 1) {
			ArrayList<BookStand> list = ResourcesManager.ac.listBookStand;
			int period = sizebookstand;
			for (int i = 0; i < result.length; i++) {
				String name = result[i];
				if (!"".equals(name) && name != null && name.contains("http:")) {
					String[] listElm = name.split("/");
					nameimg = listElm[listElm.length - 1];
					nameimg = nameimg.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\s]", "");
					System.out.println(nameimg + "=====================");
					String imagePath = Environment
							.getExternalStorageDirectory().toString()
							+ Config.IMAGE_STAND + "/" + nameimg;
					File f = new File(imagePath);
					list.get(i + period).setImage(nameimg);
					Bitmap bitmap = decodeFile(f);
					if(ResourcesManager.ac.height > 1000){
						list.get(i + period)
						.setBitmap(
								Bitmap.createScaledBitmap(bitmap, 9*ResourcesManager.ac.width/20, 9*160*ResourcesManager.ac.width/(20*340), false));
					}else{
						list.get(i + period).setBitmap(bitmap);
					}
					
				} else {
					Drawable drawable = ResourcesManager.ac.getResources()
							.getDrawable(R.drawable.no_img);
					if (drawable instanceof BitmapDrawable) {
						list.get(i + period)
								.setBitmap(
										Bitmap.createScaledBitmap(
												((BitmapDrawable) drawable)
														.getBitmap(),
														 9*ResourcesManager.ac.width/20, 9*160*ResourcesManager.ac.width/(20*340), false));
					}
				}
			}
			LayoutMainScreen.getInstance().mAdapterBookStand
					.setListNewBook(list);
			LayoutMainScreen.getInstance().mAdapterBookStand
					.notifyDataSetChanged();
			ResourcesManager.ac.waitDialog.hide();
			try {
				XMLProvider.creatBookStand(list);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (type == 2) {
			//
			ArrayList<BookRecent> list = ResourcesManager.ac.listBookInListBookStand;
			int period = MainActivity.sizeListbookInBookStand;			
			for (int i = 0; i < result.length; i++) {
				String name = result[i];
				if (!"".equals(name) && name != null && name.contains("http:")) {
					String[] listElm = name.split("/");
					nameimg = listElm[listElm.length - 1];
					nameimg = nameimg.replaceAll(
							"[/\n\r\t\0\f`\\?\\*\\<>|\":\\s]", "");
					String imagePath = Environment
							.getExternalStorageDirectory().toString()
							+ Config.IMAGE_STAND_INLIST + "/" + nameimg;
					File f = new File(imagePath);
					Bitmap bitmap = decodeFile(f);
					System.out.println(bitmap+"aaaaaa==========="+i);
					list.get(i + period).setImage(nameimg);
					Bitmap bmp = Bitmap.createScaledBitmap(bitmap,
							 ResourcesManager.ac.width / 5,
							ResourcesManager.ac.height / 6, true);
					list.get(i +period).setBitmap(bmp);

				} else {
					Drawable drawable = ResourcesManager.ac.getResources()
							.getDrawable(R.drawable.no_book_cover);
					if (drawable instanceof BitmapDrawable) {
						Bitmap bmp = Bitmap.createScaledBitmap(((BitmapDrawable) drawable).getBitmap(),
								ResourcesManager.ac.width/5,
								ResourcesManager.ac.height/6 , true);
						list.get(i+period).setBitmap(bmp);
					}

				}
			}
			LayoutManager.getInstance().removeView(
					LayoutManager.getInstance().getCurrentView());			
			LayoutGridBook.getInstance().show();
			LayoutGridBook.getInstance().list = ResourcesManager.ac.listBookInListBookStand;
			LayoutGridBook.getInstance().onLoadListener();
			ResourcesManager.ac.waitDialog.hide();			
		}

	}

	public static Bitmap decodeFile(File f) {
		Bitmap b = null;
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;

			FileInputStream fis = new FileInputStream(f);
			try {
				BitmapFactory.decodeStream(fis, null, o);
			} finally {
				fis.close();
			}

			int scale = 1;
			for (int size = Math.max(o.outHeight, o.outWidth); (size >> (scale - 1)) > 2048; ++scale)
				;
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			fis = new FileInputStream(f);
			try {
				b = BitmapFactory.decodeStream(fis, null, o2);
			} finally {
				fis.close();
			}
		} catch (IOException e) {
		}		
		if (b == null) {
			Drawable drawable = ResourcesManager.ac.getResources().getDrawable(
					R.drawable.no_book_cover);
			if (drawable instanceof BitmapDrawable) {
				b = ((BitmapDrawable) drawable).getBitmap();
			}
		}
		return b;
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub

	}

}
